<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\BatchAction\BatchPatentApplyReview;
use App\Admin\Actions\Review\PatentReviewPost;
use App\Admin\Actions\Tools\AssignAgencyBatchAction;
use App\Admin\Actions\Tools\PatentApplyFundingBatchAction;
use App\Admin\Controllers\Actions\Post\PatentAssessPost;
use App\Extensions\Actions\Post\GrantPatentPost;
use App\Extensions\Actions\Upload\PatentApplyFileUploadAction;
use App\Http\Controllers\Controller;
use App\PatentApply;
use App\Repositories\PatentApplyRepository;
use App\Services\PatentApplyService;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Support\Facades\DB;
use PhpOffice\PhpWord\IOFactory;

class PatentApplyController extends Controller
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '专利申请前评估';
    protected $service;
    public $repository;

    public function __construct(PatentApplyService $service, PatentApplyRepository $repository)
    {
        $this->service = $service;
        $this->repository = $repository;
    }

    protected function title($type)
    {
        return $type;
    }

    public function index(Content $content): Content
    {
        $grid = $this->grid(1);
        $this->header($grid);
        //$grid->disableExport(false);
        //$grid->exporter((new PatentApplyExporter())->setRoleType(1)->setFileName('专利申请中' . date('Ymd')));
        $grid->hideColumns(['score_template', 'table', 'file', 'review_status']);
        $grid->tools(function (Grid\Tools $tools) {
            if (config('settings.patent_s_ratio_show')) {
                $tools->append(new PatentApplyFundingBatchAction());
            }
        });
        return $content
            ->title('专利申请中')
            ->body($grid);
    }

    public function review(Content $content): Content
    {
        config(['admin.patent.apply.cert.show' => false]);
        $grid = $this->grid(0);
        $grid->batchActions(function (Grid\Tools\BatchActions $batchActions) {
            $batchActions->add(new BatchPatentApplyReview());
        });
        $grid->tools(function (Grid\Tools $tools) {
//            if (config('settings.module.expert_module')) {
//                $tools->append(new AssignExpertBatchAction());
//            }
            $tools->append(new AssignAgencyBatchAction());
        });
        //$grid->disableExport(false);
        //$grid->exporter((new PatentApplyExporter())->setRoleType(1)->setFileName('专利申请前评估' . date('Ymd')));
        return $content
            ->title('专利申请前评估')
            ->body($grid);
    }

    public function fail(Content $content): Content
    {
        config(['admin.patent.apply.cert.show' => false]);
        $grid = $this->grid(2);
        $grid->disableActions();
        return $content
            ->title('专利申请前评估未通过')
            ->body($grid);
    }

    protected function grid($step): Grid
    {
        $user = Admin::user();
        $grid = $this->repository->adminGrid();
        $grid->model()->where('review_status', $step);
        $this->service->gridColumns($grid, 1, 0);
        $grid->disableCreateButton();
        //$grid->disableExport();
        $grid->actions(function (Grid\Displayers\Actions $actions) use ($user) {
            $actions->disableView();
            $actions->disableDelete();
            $actions->disableEdit();
            if (!$actions->row->review_status) {
                $actions->prepend(new PatentAssessPost($actions));
                $actions->prepend(new PatentReviewPost($actions));
            } elseif ($actions->row->review_status == 1 && !$actions->row->status) {
                $actions->prepend(new GrantPatentPost($actions));
            }
            if ($user->id == 1) {
                $actions->prepend(new PatentApplyFileUploadAction($actions));
            }
        });
        return $grid;
    }

    public function download($id)
    {
        $model = $this->repository->find($id);
        if (!$model) {
            return response()->view('errors.404');
        }
        return $this->service->downloadTable($model);
    }

    public function preview($id)
    {
        $model = $this->repository->find($id);
        $templateProcessor = $this->service->tableTemplateProcessor($model);
        $wordfile = IOFactory::load($templateProcessor->save());
        $xmlWriter = IOFactory::createWriter($wordfile, "HTML"); // 转换为html
        $html = $xmlWriter->getContent(); // html内容获取
        echo $html;
    }

    protected function form()
    {
        return $this->repository->form();
    }

    public function destroy($id)
    {
        return $this->form()->destroy($id);
    }

    protected function header(Grid $grid)
    {
        $grid->header(function () {
            $year = request()->get('year') ?: date('Y');
            $data = PatentApply::query()
                ->select(DB::raw('count(*) as count,patent_type_id'))
                ->where('year', $year)
                ->where('dept_review_status', 1)
                ->where('review_status', 1)->groupBy(['patent_type_id'])->get()->map(function ($item) {
                    return [
                        'name'  => data_get(patent_type_select_option(), $item['patent_type_id']),
                        'value' => $item['count']
                    ];
                })->pluck('value', 'name')->toArray();
            $title = $year . '年(申请):';
            return view('admin.statistics.common-table-header', compact('data', 'title'));
        });
    }

}
